package cn.xiaopengstack.domain.agent.service.execute.flow.node;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.adapter.repository.IAgentRepository;
import cn.xiaopengstack.domain.agent.model.entity.ExecuteCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentClientFlowConfigVO;
import cn.xiaopengstack.domain.agent.service.execute.flow.AbstractExecuteSupport;
import cn.xiaopengstack.domain.agent.service.execute.flow.factory.DefaultFlowAgentExecuteStrategyFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jiangyangang
 */
@Component("flowExecuteRootNode")
@Slf4j
public class RootNode extends AbstractExecuteSupport {

    @Resource
    private IAgentRepository iAgentRepository;

    @Override
    protected String doApply(ExecuteCommandEntity requestParameter, DefaultFlowAgentExecuteStrategyFactory.DynamicContext dynamicContext) throws Exception {
        Map<String, AiAgentClientFlowConfigVO> stringAiAgentClientFlowConfigVOMap = iAgentRepository.queryAiAgentClientFlowConfig(requestParameter.getAiAgentId());
        dynamicContext.setAiAgentClientFlowConfigVOMap(stringAiAgentClientFlowConfigVOMap);
        dynamicContext.setStatus(DefaultFlowAgentExecuteStrategyFactory.DynamicContext.INITIALIZING);
        dynamicContext.setStartTime(System.currentTimeMillis());
        dynamicContext.setCompleted(false);
        dynamicContext.setCurrentTask(requestParameter.getMessage());
        dynamicContext.setExecutionHistory(new StringBuilder());
        dynamicContext.setDataObjects(new HashMap<>());
        dynamicContext.setStartTime(System.currentTimeMillis());
        dynamicContext.setEmitter(requestParameter.getEmitter());
        dynamicContext.setStep(0);

        return router(requestParameter, dynamicContext);
    }


    @Override
    public StrategyHandler<ExecuteCommandEntity, DefaultFlowAgentExecuteStrategyFactory.DynamicContext, String> get(ExecuteCommandEntity requestParameter, DefaultFlowAgentExecuteStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return getBean("flowMcpToolsAnalysisNode");
    }
}
